package com.zenithmind.exam.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zenithmind.exam.pojo.entity.ExamQuestionRel;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Delete;

import java.util.List;

/**
 * 考试题目关联Mapper接口
 * 
 * @author ZenithMind
 * @since 2024-07-01
 */
@Mapper
public interface ExamQuestionRelMapper extends BaseMapper<ExamQuestionRel> {

    /**
     * 根据考试ID查询题目关联列表
     * 
     * @param examId 考试ID
     * @return 题目关联列表
     */
    @Select("SELECT * FROM exam_question_rel WHERE exam_id = #{examId} ORDER BY question_order ASC")
    List<ExamQuestionRel> selectByExamId(@Param("examId") String examId);

    /**
     * 根据题目ID查询考试关联列表
     * 
     * @param questionId 题目ID
     * @return 考试关联列表
     */
    @Select("SELECT * FROM exam_question_rel WHERE question_id = #{questionId}")
    List<ExamQuestionRel> selectByQuestionId(@Param("questionId") String questionId);

    /**
     * 根据考试ID删除所有题目关联
     * 
     * @param examId 考试ID
     * @return 删除行数
     */
    @Delete("DELETE FROM exam_question_rel WHERE exam_id = #{examId}")
    int deleteByExamId(@Param("examId") String examId);

    /**
     * 根据题目ID删除所有考试关联
     * 
     * @param questionId 题目ID
     * @return 删除行数
     */
    @Delete("DELETE FROM exam_question_rel WHERE question_id = #{questionId}")
    int deleteByQuestionId(@Param("questionId") String questionId);

    /**
     * 查询考试中的题目ID列表
     * 
     * @param examId 考试ID
     * @return 题目ID列表
     */
    @Select("SELECT question_id FROM exam_question_rel WHERE exam_id = #{examId} ORDER BY question_order ASC")
    List<String> selectQuestionIdsByExamId(@Param("examId") String examId);

    /**
     * 统计考试中的题目数量
     * 
     * @param examId 考试ID
     * @return 题目数量
     */
    @Select("SELECT COUNT(*) FROM exam_question_rel WHERE exam_id = #{examId}")
    Integer countByExamId(@Param("examId") String examId);

    /**
     * 查询考试中指定类型的题目数量
     * 
     * @param examId 考试ID
     * @param questionType 题目类型
     * @return 题目数量
     */
    @Select("SELECT COUNT(*) FROM exam_question_rel eqr " +
            "INNER JOIN exam_question eq ON eqr.question_id = eq.id " +
            "WHERE eqr.exam_id = #{examId} AND eq.type = #{questionType}")
    Integer countByExamIdAndType(@Param("examId") String examId, @Param("questionType") Integer questionType);

    /**
     * 查询考试的总分
     * 
     * @param examId 考试ID
     * @return 总分
     */
    @Select("SELECT COALESCE(SUM(score), 0) FROM exam_question_rel WHERE exam_id = #{examId}")
    Integer sumScoreByExamId(@Param("examId") String examId);

    /**
     * 批量插入考试题目关联
     * 
     * @param examQuestionRels 考试题目关联列表
     * @return 插入行数
     */
    int batchInsert(@Param("list") List<ExamQuestionRel> examQuestionRels);
}
